<?php
// +----------------------------------------------------------------------
// | Description: 基础类，无需验证权限。
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\logic\AdminLogic;
use app\common\validate\AdminValidate;
use app\common\controller\BaseController;
use app\common\model\Admin;
use app\common\model\ES\base\ESTest;
use app\common\model\SystemConfig;
use app\common\event\AdminLogout;
use think\captcha\facade\Captcha;
use hg\apidoc\annotation as Apidoc;
/**
 * 后台管理员
 * Class Tool
 * @package app\admin\controller
 * @Apidoc\Title("工具")
 */
class Tool extends BaseController
{
    /**
     * @Apidoc\Title("登录")
     * @Apidoc\Desc("登录")
     * @Apidoc\Url("/admin/tool/login")
     * @Apidoc\Method("post")
     * @Apidoc\Tag("admin")
     * @Apidoc\Header("admin-token", require=false, desc="Token")
     * @Apidoc\Param("username", type="string|length:2,12",require=true, default="admin", desc="用户名")
     * @Apidoc\Param("password", type="string|length:5,20",require=true, default="225851", desc="密码")
     * @Apidoc\Param("isRemember", type="integer",require=true, default="1", desc="记住登陆")
     * @Apidoc\Returned("{}",type="object",desc="null",default="0")
     */
    public function login($relogin = false)
    {
        $AdminService = AdminLogic::instance();
        $param = input_param([
            'username' => '',
            'password' => '',
            'captcha' => '',
            'isRemember' => '',
        ]);
        //检测
        AdminValidate::instance()->runCheck($param, '', __FUNCTION__);
        //登录
        $userInfo = $AdminService->login();
        $userInfo->hidden(['password']);
        $data['userInfo'] = $userInfo->toArray();
        $data['menusList'] = $AdminService->getMenuList($userInfo);
        $data['token'] = $AdminService->createJwt($userInfo);
        $data['expire'] = config('jwt_config.exp_time');
        //重新登录
        if ($relogin||$param['isRemember']) {
            $secret['username'] = $param['username'];
            $secret['password'] = $param['password'];
            $data['rememberKey'] = encrypt($secret);
        }
        return $this->json_responce($data);
    }

    /**
     * 重新登录
     * @return \think\response\Json
     * @throws \app\common\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function relogin()
    {
        return $this->login(true);
    }

    /**
     * 注销
     * @return \think\response\Json
     */
    public function logout()
    {
        $param = $this->param;
        event(AdminLogout::class);
        return $this->json_responce('退出成功');
    }

    /**
     * 获取配置
     * @return \think\response\Json
     */
    public function getConfigs()
    {
        $SystemConfigModel = SystemConfig::instance();
        $systemConfig = cache('DB_CONFIG_DATA');
        if (!$systemConfig) {
            //获取所有系统配置
            $systemConfig = $SystemConfigModel->getDataList();
            cache('DB_CONFIG_DATA', null);
            cache('DB_CONFIG_DATA', $systemConfig, 36000); //缓存配置
        }
        return $this->json_responce($systemConfig);
    }

    /**
     * 获取验证码
     * @return mixed
     */
    public function getVerify()
    {
        return $this->captcha();
    }

    /**
     * 修改密码
     * @return \think\response\Json
     */
    public function setInfo()
    {
        $Admin = Admin::instance();
        $param = input_param([
            'old_pwd' => '',
            'new_pwd' => '',
            'auth_key' => '',
            'isRemember' => '',
        ]);
        AdminValidate::instance()->runCheck($param, '', __FUNCTION__);
        $data = $Admin->setInfo($param['auth_key'], $param['old_pwd'], $param['new_pwd']);
        return $this->json_responce($data);
    }

    /**
     * 验证码
     * @return mixed
     */
    public function captcha()
    {
        return Captcha::create();
    }

    /**
     * 校验验证码
     * @return \think\response\Json
     */
    public function checkCaptcha()
    {
        $captcha = input('get.captcha');
        $id = AdminValidate::instance()->getCaptchaId();
        return $this->json_responce(captcha_check($captcha, $id));
    }

    public function testInsert()
    {
        $ESTest_obj = ESTest::instance();
        $body = array(
            [
                'content' => '美国留给伊拉克的是个烂摊子吗',
                'name' => '美国留给伊拉克',
            ],
            [
                'content' => '公安部：各地校车将享最高路权',
                'name' => '公安部各地校车',
            ],
            [
                'content' => '中韩渔警冲突调查：韩警平均每天扣1艘中国渔船',
                'name' => '中韩渔警冲突',
            ],
            [
                'content' => '中国驻洛杉矶领事馆遭亚裔男子枪击 嫌犯已自首',
                'name' => '中国驻洛杉矶领事馆',
            ],
        );
        $ESTest_obj->deleteAll();
        $res = $ESTest_obj->insert($body);
        return $this->json_responce();
    }

    public function testSearch()
    {
        $ESTest_obj = ESTest::instance();
        $res = $ESTest_obj->search('name', '中国');
        return $this->json_responce($res);
    }

    public function testParams()
    {
        $post = $this->request->post();
        return $this->json_responce($post);
    }
}
